# -*- coding:utf-8 -*-
"""
@author: 登陆
@file: account.py
@time: 2023/12/13 14:51
@desc: 
"""
import requests
from django.shortcuts import render, HttpResponse, redirect
from app01.utils.bootstrap import BootStrapForm
from django import forms
from app01.utils.encrypt import md5
from app01 import models
from app01.utils.code import check_code


class LoginForm(BootStrapForm):
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput,
        required=True
    )
    password = forms.CharField(
        label="密 码",
        widget=forms.PasswordInput(render_value=True),
        required=True
    )

    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
        required=True
    )

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)

# class LoginModelForm(forms.ModelForm):
#     class Meta:
#         model = models.Admin
#         fields = ['username', 'password']

def login(request):
    """ 登陆 """
    if request.method == "GET":
        form = LoginForm()
        return render(request, 'login.html', {'form': form})

    form = LoginForm(data=request.POST)
    if form.is_valid():

        # 校验验证码
        user_input_code = form.cleaned_data.pop('code')
        img_code = request.session.get('image_code', '')
        if img_code.upper() != user_input_code.upper():
            form.add_error("code", "验证码错误")
            return render(request, 'login.html', {'form': form})

        # 验证成功,获取到的用户名和密码
        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password", "用户名或密码错误")
            return render(request, 'login.html', {'form': form})

        # 用户名和密码正确
        request.session['info'] = {'id':admin_object.id, 'name': admin_object.username}
        # session信息可以保存7天
        request.session.set_expiry(60 * 60 * 24 * 7)
        # 网站生成随机字符串; 写到用户浏览器的COOKIE中; 在写入到session中
        return redirect('/admin/list/')

    return render(request, 'login.html', {'form': form})


def logout(request):
    """ 退出 """
    request.session.clear()
    return redirect('/login/')


from io import BytesIO
def image_code(request):
    """ 生成图片验证码 """
    # 调用Pillow函数, 生成图片
    img, code_string = check_code()
    print(code_string)

    # 写入到自己的session中(以便检验验证码)
    request.session['image_code'] = code_string
    # 让验证码在session中保留时效
    request.session.set_expiry(60)

    stream = BytesIO()
    img.save(stream, 'png')

    return HttpResponse(stream.getvalue())